package com.grj.parkingsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.grj.parkingsystem.entity.ParkingLot;
import com.grj.parkingsystem.entity.ParkingSpace;
import com.grj.parkingsystem.mapper.ParkingSpaceMapper;
import com.grj.parkingsystem.service.ParkingLotService;
import com.grj.parkingsystem.mapper.ParkingLotMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
* @author ganru
* @description 针对表【t_parking_lot(停车场表)】的数据库操作Service实现
* @createDate 2025-05-16 16:51:44
*/
@Service
public class ParkingLotServiceImpl extends ServiceImpl<ParkingLotMapper, ParkingLot>
    implements ParkingLotService{

    @Resource
    private ParkingSpaceMapper parkingSpaceMapper;

    @Override
    public List<ParkingLot> getNearbyParkings(double latitude, double longitude, double radius) {
        // 计算经纬度范围
        double latRange = radius / 111.0;
        double lngRange = radius / (111.0 * Math.cos(Math.toRadians(latitude)));

        double minLat = latitude - latRange;
        double maxLat = latitude + latRange;
        double minLng = longitude - lngRange;
        double maxLng = longitude + lngRange;

        return baseMapper.selectList(new QueryWrapper<ParkingLot>()
                .ge("latitude", minLat)
                .le("latitude", maxLat)
                .ge("longitude", minLng)
                .le("longitude", maxLng)
                .eq("status", 1));
    }

    @Override
    @Transactional
    public boolean updateAvailableSpaces(Long parkingLotId, int change) {
        ParkingLot parkingLot = baseMapper.selectById(parkingLotId);
        if (parkingLot == null) {
            return false;
        }

        int newAvailable = parkingLot.getAvailableSpaces() + change;
        if (newAvailable < 0 || newAvailable > parkingLot.getTotalSpaces()) {
            return false;
        }

        parkingLot.setAvailableSpaces(newAvailable);
        return updateById(parkingLot);
    }

    @Override
    public List<ParkingSpace> getParkingSpaces(Long parkingLotId) {
        return parkingSpaceMapper.selectList(new QueryWrapper<ParkingSpace>().eq("parking_lot_id", parkingLotId));
    }
}




